package com.nice.rm.core;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.nice.rm.util.FileUtil;

/**
 * 
 * 负责回收过期的索引文件,释放磁盘空间
 * 
 * @author cdyf-2015年5月4日
 */
public class ExpireIndexFileGCService implements Runnable {

    private static final Logger log = LoggerFactory.getLogger(ExpireIndexFileGCService.class);

    private File indexDir;
    private volatile boolean isRunning;
    private ScheduledExecutorService scheduledService;

    public ExpireIndexFileGCService(File indexDir) {
	this.scheduledService = Executors.newSingleThreadScheduledExecutor();
	this.indexDir = indexDir;
    }

    public void start() {
	if (isRunning)
	    return;
	isRunning = true;
	scheduledService.scheduleAtFixedRate(this, 0, 10, TimeUnit.SECONDS);
    }

    public void shutdown() {
	scheduledService.shutdownNow();
    }

    @Override
    public void run() {
	Thread.currentThread().setName("Expire-Index-File-GC");
	File file = new File(indexDir, PersistentService.LAST_INDEX_DIR);
	try {
	    if (file.exists() && indexDir.canRead()) {
		FileInputStream fis = new FileInputStream(file);
		DataInputStream dis = new DataInputStream(fis);
		long index = dis.readLong();// lastFileIndex
		// dis.readLong();// lastSaveTime
		// dis.readLine();//lastIndexDirName
		FileUtil.close(fis, dis);
		File[] files = indexDir.listFiles();
		for (File tmp : files) {
		    isIndexFile(tmp, index);
		}

	    }
	} catch (Exception e) {
	    log.error("ExpireIndexFileGC Thread error", e);
	}

    }

    private void isIndexFile(File tmp, long index) {
	if (tmp.isFile())
	    return;
	String name = tmp.getName();
	if (!name.startsWith(RealTimeIndexManager.INDEX_DIR_SUFFIX))
	    return;
	long idx = Long.valueOf(name.substring(name.lastIndexOf("_") + 1));
	if (idx < index) {
	    FileUtil.deleteFile(tmp);
	}
    }
}
